#include "cgic.h"
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <sys/vfs.h>
#include "cgi_interface.h"
#include "session.h"
#define CK_TIME 1  
// 接口参数：
// 1.room_id
// 2.method
// 3.method = set暂时不支持 只能get
// 

char *success_json="{\"STATUS\":\"SUCCESS\"}";
char *success_json2="{"
					"\"STATUS\":\"SUCCESS\","
					"\"FREE_RAM\":\"%d\",\"TOTAL_RAM\":\"%d\",\"RAM_PERCENT\":\"%d\","
					"\"ROOT_SIZE\":\"%d\",\"ROOT_A\":\"%d\",\"ROOT_USE\":\"%d\",\"ROOT_PERCENT\":\"%d\","
					"\"CPU_NPROCS\":\"%d\",\"CPU_PERCENT\":\"%d\","
					"\"UPTIMES\":\"%d\","
					"\"DEVICE_ONLINE\":\"%d\","
					"\"SMOG_STATUS\":%s"
					"}";
char *faild_json="{\"STATUS\":\"FAIL\",\"ERROR\":\"%s\"}";
void error_printf(cgiFormResultType ret,char *str,char* out);

unsigned long get_file_size(const char *filename)
{      
    struct stat buf;
    
    if(stat(filename, &buf)<0)  
    {   
        return 0;
    }
    
    return (unsigned long)buf.st_size;
} 

int cgiMain() {
	
	int room_id;
	int temp_value;
	int ret;
	char json_data[256];
	char method[4];
	char token[18];
	char out[1024];
	char dev_mac[256];
	
	//这里为了能够跨域还要能带COOKIE 做点操作
	fprintf(cgiOut,"Access-Control-Allow-Credentials: true\r\n");
	if(cgiOrigin){
		sprintf(out,"Access-Control-Allow-Origin: %s\r\n",cgiOrigin);
		fprintf(cgiOut,out); 
	}else{
		fprintf(cgiOut,"Access-Control-Allow-Origin: *\r\n");
	}
	
	
	cgiHeaderContentType("text/html");
	
 	ret = cgiCookieString("token", token,17);//获取用户的token
	if(ret!=cgiFormSuccess){
		//token有问题小老弟 没有从cookie中获取到token
		//试试其他方法获取
		ret = cgiFormString("token", token, 17);
		if(ret!=cgiFormSuccess){
			// 两种方法都没获取到
			fprintf(cgiOut,"{\"STATUS\":\"FAIL\",\"ERROR\":\"No Login\"}");
			return 0;
		}
		
	}
	
	
	if(!has_session(token)){
		//没登录就想访问
		fprintf(cgiOut,"{\"STATUS\":\"FAIL\",\"ERROR\":\"No Login\"}");
		return 0;
	} 
	
	ret = cgiFormString("dev_mac",dev_mac,256);  //判断dev_mac是否有提交
	if(ret!=cgiFormSuccess){
		error_printf(ret,"dev_mac",json_data);
		fprintf(cgiOut,json_data);
		return 0;
	}
	
	int root_percent,root_total,root_a,root_use; //根文件系统使用情况
	int mem_percent,mem_total,mem_free; //内存使用情况
	int cpu_percent,cpu_nprocs;  //CPU利用率
	int uptimes; //系统启动多长时间
	
	//获取内存使用情况及系统启动时间
	struct sysinfo s_info;
	ret = sysinfo(&s_info);
	if(ret==0){
		/* int memfree = tmp.freeram/(1024*1024);
		int memtotal = tmp.totalram/(1024*1024);
		sprintf(out,success_json2,memfree,memtotal);
		fprintf(cgiOut,out); */
      /*   printf("Uptime = %lds\nLoad: 1 min %lu / 5 min %lu / 15 min %lu\n"
                 "RAM: total %lu / free %lu / shared %lu\n"
                 "Memory in buffers = %lu\nSwap: total %lu / free %lu\n"
                 "Number of processes = %d\n",
                 s_info.uptime, s_info.loads[0],
                 s_info.loads[1], s_info.loads[2],
                 s_info.totalram, s_info.freeram,
                 s_info.sharedram, s_info.bufferram,
                 s_info.totalswap, s_info.freeswap,
                 s_info.procs); */
		mem_total = s_info.totalram/(1024*1024);
		mem_free = s_info.freeram/(1024*1024);
		mem_percent = (float)(mem_total-mem_free)/mem_total*100;
		uptimes = s_info.uptime;
		
	}else{
		error_printf(100,"sysinfo",json_data);
		fprintf(cgiOut,json_data);
		return 0;
	}
	
	
	//获取CPU利用率
	FILE * fp;
	char buf[128];
	char cpu[5]; 
	long int all1,all2,idle1,idle2; 
	float usage;  
	fp = fopen("/proc/stat","r");  
	if(fp==NULL){
		error_printf(100,"fopen",json_data);
		fprintf(cgiOut,json_data);
	}else{
		int user,nice,sys,idle,iowait,irq,softirq;
		fgets(buf,sizeof(buf),fp);  
		sscanf(buf,"%s%d%d%d%d%d%d%d",cpu,&user,&nice,&sys,&idle,&iowait,&irq,&softirq);  
		all1 = user+nice+sys+idle+iowait+irq+softirq;  
		idle1 = idle;  
		rewind(fp);  
		//第二次读数据
		sleep(CK_TIME);
		memset(buf,0,sizeof(buf)); 
		cpu[0] = '\0';
		user=nice=sys=idle=iowait=irq=softirq=0;  
		fgets(buf,sizeof(buf),fp); 
		sscanf(buf,"%s%d%d%d%d%d%d%d",cpu,&user,&nice,&sys,&idle,&iowait,&irq,&softirq); 
		all2 = user+nice+sys+idle+iowait+irq+softirq;  
        idle2 = idle; 
		usage = (float)((all2-all1)-(idle2-idle1))/(all2-all1) ;  		
		
		 /* printf("all=%d\n",all2-all1);  
                printf("ilde=%d\n",idle2-idle1);  
                printf("cpu use = %.2f\%\n",usage);    */
				
		cpu_percent = usage*100; //处理器使用率
		if(cpu_percent>100)cpu_percent=100;
		cpu_nprocs = get_nprocs_conf();
		
	}
	fclose(fp);
	
	//获取根文件系统使用情况
	struct statfs sfs;
	int i = statfs("/",&sfs);
	root_percent = (sfs.f_blocks - sfs.f_bfree) *100 /(sfs.f_blocks - sfs.f_bfree + sfs.f_bavail)+1;
	root_total = 4*sfs.f_blocks/1024/1000;
	root_a = 4*sfs.f_bavail/1024/1000;
	root_use = 4*(sfs.f_blocks - sfs.f_bfree)/1024/1000;
		


/* char *success_json2="{\
					  \"STATUS\":\"SUCCESS\",\
					  \"FREE_RAM\":\"%d\",\"TOTAL_RAM\":\"%d\",\"RAM_PERCENT\":\"%d\"\
					  \"ROOT_SIZE\":\"%d\",\"ROOT_A\":\"%d\",\"ROOT_USE\":\"%d\",\"ROOT_PERCENT\":\"%d\"\
					  \"CPU_NPROCS\":\"%d\",\"CPU_PERCENT\":\"%d\",\
					  }"; */
					  
					  
	int device_online=CGI_Get_Online_DEV_Count();		
	int smog_status =  CGI_Get_Smoke_Status(dev_mac);
	sprintf(out,success_json2,mem_free,mem_total,mem_percent,root_total,root_a,root_use,root_percent,cpu_nprocs,cpu_percent,uptimes,device_online,smog_status?"true":"false");
	fprintf(cgiOut,out);
	return 0;
	
}


void error_printf(cgiFormResultType ret,char *str,char* out){
	char err_str[100];
	switch(ret){
		case cgiFormBadType:
			sprintf(err_str,"%s %s",str,"BadType");
			break;
		case cgiFormEmpty:
			sprintf(err_str,"%s %s",str,"Empty");
			break;
		case cgiFormNotFound:
			sprintf(err_str,"%s %s",str,"NotFound");
			break;
			
		default:
			//other error
			sprintf(err_str,"%s %s",str,"other error");
			break;
	}
	sprintf(out,faild_json,err_str);
}
